package org.pettyfox.pfpay.utils;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class BeanMapUtil {
    private static DateTimeFormatter fmt;

    /**
     * 时间类型自动格式化为字符串
     * @param obj
     * @return
     */
    public static Map<String, Object> objectToMap(Object obj){
        if(obj == null)
            return null;

        Map<String, Object> map = new HashMap<String, Object>();

        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(obj.getClass());

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                //默认PropertyDescriptor会有一个class对象，剔除之
                if (key.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method getter = property.getReadMethod();
                Object value = getter!=null ? getter.invoke(obj) : null;
                if(value instanceof Date){
                    if(null ==fmt){
                        fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                    }
                    value = fmt.print(((Date)value).getTime());
                }
                map.put(key, value);
            }
            return map;
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
